import { useState, useEffect } from 'react';
import { Card, Row, Col, Table, Tag, Progress, Button, Statistic, Alert, Descriptions, Space, Typography, Divider, message, Tooltip, Popconfirm } from 'antd';
import { ReloadOutlined, DeleteOutlined, WifiOutlined, MessageOutlined, UserOutlined, WarningOutlined, DisconnectOutlined } from '@ant-design/icons';
import { formatTimestamp } from '../utils/timeUtils';

const { Title, Text } = Typography;

// 简单的API调用函数
const apiCall = async (url: string, method: 'GET' | 'POST' = 'GET') => {
  const response = await fetch(url, {
    method,
    headers: {
      'Content-Type': 'application/json',
    },
  });
  return response.json();
};

interface ConnectionInfo {
  user_id: string;
  user_display_name?: string;  // 添加显示名称字段
  user_type: string;
  connection_uuid: string;
  ip: string;
  connected_at: string;
  last_heartbeat: string;
  message_count: number;
  connection_state: number;
}

interface WebSocketStats {
  total_users: number;
  total_connections: number;
  c_users_count: number;
  b_users_count: number;
  c_users: string[];
  b_users: string[];
  message_stats: {
    total_sent: number;
    total_failed: number;
    total_received: number;
  };
}

interface MonitorData {
  overview: WebSocketStats;
  connections: ConnectionInfo[];
  stale_connections: ConnectionInfo[];
  health_score: number;
  timestamp: string;
}

export default function WebSocketMonitorPage() {
  const [monitorData, setMonitorData] = useState<MonitorData | null>(null);
  const [loading, setLoading] = useState(false);
  const [cleanupLoading, setCleanupLoading] = useState(false);
  const [autoRefresh, setAutoRefresh] = useState(true);
  const [duplicateInfo, setDuplicateInfo] = useState<{ original: number; cleaned: number } | null>(null);

  const fetchMonitorData = async () => {
    setLoading(true);
    try {
      const response = await apiCall('/api/websocket/monitor');
      if (response.success) {
        // 对连接数据进行去重处理
        const originalConnections = response.data.connections || [];
        const originalStaleConnections = response.data.stale_connections || [];
        const cleanedConnections = deduplicateConnections(originalConnections);
        const cleanedStaleConnections = deduplicateConnections(originalStaleConnections);
        
        // 记录去重信息
        const totalOriginal = originalConnections.length + originalStaleConnections.length;
        const totalCleaned = cleanedConnections.length + cleanedStaleConnections.length;
        
        if (totalOriginal !== totalCleaned) {
          setDuplicateInfo({ original: totalOriginal, cleaned: totalCleaned });
        } else {
          setDuplicateInfo(null);
        }
        
        const cleanedData = {
          ...response.data,
          connections: cleanedConnections,
          stale_connections: cleanedStaleConnections
        };
        setMonitorData(cleanedData);
      } else {
        console.error('API returned error:', response);
        message.error('获取监控数据失败');
      }
    } catch (error) {
      console.error('Failed to fetch monitor data:', error);
      message.error('连接监控服务失败，请检查后端服务是否正常');
    } finally {
      setLoading(false);
    }
  };

  // 连接去重函数
  const deduplicateConnections = (connections: ConnectionInfo[]): ConnectionInfo[] => {
    const connectionMap = new Map<string, ConnectionInfo>();
    
    connections.forEach(conn => {
      // 对于B端用户，如果有多个连接，优先保留最新的心跳时间
      const key = `${conn.user_id}-${conn.connection_uuid}`;
      const existing = connectionMap.get(key);
      
      if (!existing) {
        connectionMap.set(key, conn);
      } else {
        // 比较心跳时间，保留更新的连接
        const existingHeartbeat = existing.last_heartbeat === 'unknown' ? 0 : new Date(existing.last_heartbeat).getTime();
        const currentHeartbeat = conn.last_heartbeat === 'unknown' ? 0 : new Date(conn.last_heartbeat).getTime();
        
        if (currentHeartbeat > existingHeartbeat) {
          console.log(`替换重复连接 ${key}: 更新的心跳时间`);
          connectionMap.set(key, conn);
        } else {
          console.log(`跳过重复连接 ${key}: 心跳时间较旧`);
        }
      }
    });
    
    return Array.from(connectionMap.values()).sort((a, b) => {
      // 按用户类型排序，B端用户在前
      if (a.user_type !== b.user_type) {
        return a.user_type === 'B' ? -1 : 1;
      }
      // 同类型用户按用户ID排序
      return a.user_id.localeCompare(b.user_id);
    });
  };

  const cleanupStaleConnections = async () => {
    setCleanupLoading(true);
    try {
      const response = await apiCall('/api/websocket/cleanup', 'POST');
      if (response.success) {
        const cleanedCount = response.data?.cleaned_connections || 0;
        
        // 立即刷新数据
        await fetchMonitorData();
        
        // 显示成功消息
        if (cleanedCount > 0) {
          message.success(`已成功清理 ${cleanedCount} 个僵尸连接`);
        } else {
          message.info('没有发现需要清理的僵尸连接');
        }
      }
    } catch (error) {
      console.error('Failed to cleanup stale connections:', error);
      message.error('清理僵尸连接失败，请稍后重试');
    } finally {
      setCleanupLoading(false);
    }
  };

  // 断开特定连接的函数
  const disconnectConnection = async (userId: string, connectionUuid: string) => {
    try {
      const response = await apiCall(`/api/websocket/disconnect/${userId}/${connectionUuid}`, 'POST');
      if (response.success) {
        message.success(`已成功断开用户 ${userId} 的连接`);
        // 立即刷新数据
        await fetchMonitorData();
      } else {
        message.error(`断开连接失败: ${response.message || '未知错误'}`);
      }
    } catch (error) {
      console.error('Failed to disconnect connection:', error);
      message.error('断开连接失败，请稍后重试');
    }
  };

  useEffect(() => {
    fetchMonitorData();
  }, []);

  useEffect(() => {
    if (autoRefresh) {
      const interval = setInterval(fetchMonitorData, 5000); // 每5秒刷新
      return () => clearInterval(interval);
    }
  }, [autoRefresh]);

  const getConnectionStateText = (state: number) => {
    switch (state) {
      case 1: return <Tag color="green">已连接</Tag>;
      case 2: return <Tag color="orange">正在关闭</Tag>;
      case 3: return <Tag color="red">已关闭</Tag>;
      default: return <Tag color="default">未知</Tag>;
    }
  };

  const getUserTypeColor = (type: string) => {
    return type === 'C' ? 'blue' : 'purple';
  };

  const formatTime = (timestamp: string) => {
    if (timestamp === 'unknown') return '未知';
    try {
      return formatTimestamp(timestamp);
    } catch {
      return '未知';
    }
  };

  const getHealthColor = (score: number): "success" | "exception" | "normal" | "active" => {
    if (score >= 80) return 'success';
    if (score >= 60) return 'normal';
    return 'exception';
  };

  const columns = [
    {
      title: '👤 用户信息',
      dataIndex: 'user_id',
      key: 'user_id',
      width: 200,
      fixed: 'left' as const,
      render: (text: string, record: ConnectionInfo) => (
        <Space direction="vertical" size={2}>
          <Space size={4}>
            <Tag color={getUserTypeColor(record.user_type)} style={{ fontSize: '10px', padding: '0 4px' }}>
              {record.user_type === 'C' ? '💼 客户' : '🏢 经理'}
            </Tag>
            <Text strong style={{ fontSize: '12px' }}>
              {record.user_display_name || text}
            </Text>
          </Space>
          <Space size={2}>
            <Text type="secondary" style={{ fontSize: '10px' }}>
              ID: {text}
            </Text>
          </Space>
          <Tooltip title={`真实IP地址: ${record.ip}\n点击查看IP获取详情`}>
            <Text type="secondary" style={{ fontSize: '10px', cursor: 'pointer' }} 
                  onClick={() => {
                    message.info(`IP: ${record.ip}\n获取方式: ${record.ip.includes('127.0.0.1') || record.ip.includes('localhost') ? '本地开发环境' : '网络请求'}`, 3);
                  }}>
              📍 {record.ip === 'unknown' ? '未知IP' : record.ip}
              {record.ip.includes('127.0.0.1') && <Text style={{ color: '#1890ff', marginLeft: 4 }}>🏠</Text>}
              {record.ip.includes('192.168') && <Text style={{ color: '#52c41a', marginLeft: 4 }}>🏢</Text>}
            </Text>
          </Tooltip>
        </Space>
      ),
    },
    {
      title: '🔗 连接标识',
      dataIndex: 'connection_uuid',
      key: 'connection_uuid',
      width: 140,
      render: (text: string) => (
        <Text code title={text} style={{ fontSize: '11px' }}>
          {text.substring(0, 12)}...
        </Text>
      ),
    },
    {
      title: '📊 状态',
      dataIndex: 'connection_state',
      key: 'connection_state',
      width: 100,
      align: 'center' as const,
      render: (state: number) => getConnectionStateText(state),
    },
    {
      title: '🕒 连接时间',
      dataIndex: 'connected_at',
      key: 'connected_at',
      width: 160,
      render: (time: string) => (
        <div>
          <Text style={{ fontSize: '11px', display: 'block' }}>
            {formatTime(time).split(' ')[0]}
          </Text>
          <Text type="secondary" style={{ fontSize: '10px' }}>
            {formatTime(time).split(' ')[1]}
          </Text>
        </div>
      ),
    },
    {
      title: '💓 最后心跳',
      dataIndex: 'last_heartbeat',
      key: 'last_heartbeat',
      width: 160,
      render: (time: string) => {
        const formatted = formatTime(time);
        const isStale = time !== 'unknown' && 
          (Date.now() - new Date(time).getTime()) > 30000;
        
        return (
          <div>
            <Text 
              style={{ 
                color: isStale ? '#ff4d4f' : '#52c41a',
                fontSize: '11px',
                display: 'block'
              }}
            >
              {formatted.split(' ')[0]}
              {isStale && <WarningOutlined style={{ marginLeft: 4, fontSize: '10px' }} />}
            </Text>
            <Text type="secondary" style={{ fontSize: '10px' }}>
              {formatted.split(' ')[1]}
            </Text>
          </div>
        );
      },
    },
    {
      title: '📨 消息量',
      dataIndex: 'message_count',
      key: 'message_count',
      width: 100,
      align: 'center' as const,
      render: (count: number) => (
        <Tag color={count > 10 ? 'green' : count > 5 ? 'orange' : 'default'}>
          {count}
        </Tag>
      ),
    },
    {
      title: '🔌 操作',
      key: 'action',
      width: 120,
      fixed: 'right' as const,
      render: (_text: string, record: ConnectionInfo) => {
        const isConnected = record.connection_state === 1;
        const isStale = record.last_heartbeat !== 'unknown' && 
          (Date.now() - new Date(record.last_heartbeat).getTime()) > 30000;
        
        return (
          <Space direction="vertical" size={4}>
            <Popconfirm
              title={`确定要断开 ${record.user_id} 的连接吗？`}
              description={`连接状态: ${isConnected ? '正常' : '异常'} | ${isStale ? '心跳超时' : '心跳正常'}`}
              onConfirm={() => disconnectConnection(record.user_id, record.connection_uuid)}
              okText="确认断开"
              cancelText="取消"
              okType="danger"
            >
              <Button 
                type="primary" 
                danger
                size="small" 
                icon={<DisconnectOutlined />}
                disabled={!isConnected && !isStale}
                title={isConnected ? '强制断开连接' : isStale ? '清理僵尸连接' : '连接已断开'}
              >
                {isStale ? '清理' : '断开'}
              </Button>
            </Popconfirm>
            
            {/* 连接状态指示器 */}
            <div style={{ fontSize: '10px', textAlign: 'center' }}>
              {isConnected ? (
                <Tag color="green" style={{ fontSize: '8px', padding: '0 2px' }}>活跃</Tag>
              ) : isStale ? (
                <Tag color="orange" style={{ fontSize: '8px', padding: '0 2px' }}>僵尸</Tag>
              ) : (
                <Tag color="red" style={{ fontSize: '8px', padding: '0 2px' }}>断开</Tag>
              )}
            </div>
          </Space>
        );
      },
    },
  ];

  if (!monitorData) {
    return <div>加载中...</div>;
  }

  const { overview, connections, stale_connections, health_score, timestamp } = monitorData;
  const successRate = overview.message_stats.total_sent > 0 ? 
    ((overview.message_stats.total_sent - overview.message_stats.total_failed) / overview.message_stats.total_sent * 100).toFixed(1) : '100';

  return (
    <div style={{ padding: '24px', minHeight: '100vh', background: '#f5f5f5' }}>
      <div style={{ marginBottom: '24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: '16px' }}>
        <Title level={2} style={{ margin: 0 }}>
          <WifiOutlined style={{ marginRight: '8px' }} />
          WebSocket 监控中心
        </Title>
        <Space wrap>
          <Button 
            type="primary" 
            icon={<ReloadOutlined />} 
            onClick={fetchMonitorData}
            loading={loading}
          >
            刷新数据
          </Button>
          <Button 
            type={autoRefresh ? 'default' : 'primary'}
            onClick={() => setAutoRefresh(!autoRefresh)}
          >
            {autoRefresh ? '⏸️ 停止自动刷新' : '▶️ 开启自动刷新'}
          </Button>
          <Button 
            danger
            icon={<DeleteOutlined />}
            onClick={cleanupStaleConnections}
            disabled={stale_connections.length === 0}
            loading={cleanupLoading}
          >
            🧹 清理僵尸连接 ({stale_connections.length})
          </Button>
          <Tooltip title="断开所有活跃连接（危险操作）">
            <Popconfirm
              title="确定要断开所有活跃连接吗？"
              description="这将强制断开所有用户的WebSocket连接，请谨慎操作！"
              onConfirm={async () => {
                try {
                  // 批量断开所有活跃连接
                  const activeConnections = monitorData?.connections || [];
                  let successCount = 0;
                  
                  for (const conn of activeConnections) {
                    if (conn.connection_state === 1) { // 只断开活跃连接
                      try {
                        await disconnectConnection(conn.user_id, conn.connection_uuid);
                        successCount++;
                      } catch (error) {
                        console.error(`Failed to disconnect ${conn.user_id}:`, error);
                      }
                    }
                  }
                  
                  message.success(`已断开 ${successCount} 个活跃连接`);
                } catch (error) {
                  message.error('批量断开失败');
                }
              }}
              okText="确认断开所有"
              cancelText="取消"
              okType="danger"
            >
              <Button 
                danger
                type="dashed"
                icon={<WarningOutlined />}
                disabled={!monitorData?.connections?.some(conn => conn.connection_state === 1)}
              >
                💥 断开所有连接
              </Button>
            </Popconfirm>
          </Tooltip>
        </Space>
      </div>

      {/* 健康状态警告 */}
      {stale_connections.length > 0 && (
        <Alert
          message={`⚠️ 检测到 ${stale_connections.length} 个僵尸连接`}
          description="这些连接可能已经断开但未正确清理，建议进行清理操作以优化系统性能。"
          type="warning"
          showIcon
          style={{ marginBottom: '24px' }}
          closable
        />
      )}
      
      {/* 去重信息提示 */}
      {duplicateInfo && (
        <Alert
          message={`🔄 发现重复连接已自动去重`}
          description={`原始连接数: ${duplicateInfo.original}，去重后: ${duplicateInfo.cleaned}，已移除 ${duplicateInfo.original - duplicateInfo.cleaned} 个重复连接`}
          type="info"
          showIcon
          style={{ marginBottom: '24px' }}
          closable
        />
      )}

      {/* 概览统计 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable>
            <Statistic
              title="🏥 系统健康评分"
              value={health_score}
              suffix="/ 100"
              valueStyle={{ color: health_score >= 80 ? '#3f8600' : health_score >= 60 ? '#fa8c16' : '#cf1322' }}
              prefix={<WifiOutlined />}
            />
            <Progress 
              percent={health_score} 
              status={getHealthColor(health_score)}
              size="small"
              style={{ marginTop: '8px' }}
              strokeColor={health_score >= 80 ? '#52c41a' : health_score >= 60 ? '#faad14' : '#ff4d4f'}
            />
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable>
            <Statistic
              title="🔗 总连接数"
              value={overview.total_connections}
              prefix={<UserOutlined />}
            />
            <div style={{ marginTop: '8px', fontSize: '12px', color: '#666' }}>
              👥 活跃用户: {overview.total_users}
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable>
            <Statistic
              title="📊 消息成功率"
              value={successRate}
              suffix="%"
              prefix={<MessageOutlined />}
              valueStyle={{ color: parseFloat(successRate) >= 95 ? '#3f8600' : '#cf1322' }}
            />
            <div style={{ marginTop: '8px', fontSize: '12px', color: '#666' }}>
              📤 已发送: {overview.message_stats.total_sent}
            </div>
          </Card>
        </Col>
        <Col xs={24} sm={12} md={6}>
          <Card hoverable>
            <Statistic
              title="👥 用户分布"
              value={`${overview.c_users_count} / ${overview.b_users_count}`}
              prefix={<UserOutlined />}
            />
            <div style={{ marginTop: '8px', fontSize: '12px', color: '#666' }}>
              💼 C端/B端 | 总计: {overview.total_users}
            </div>
          </Card>
        </Col>
      </Row>

      {/* 详细统计 */}
      <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
        <Col xs={24} lg={12}>
          <Card title="📈 消息统计详情" size="small" hoverable>
            <Descriptions column={1} size="small">
              <Descriptions.Item label="📥 已接收">
                <Tag color="blue">{overview.message_stats.total_received}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="📤 已发送">
                <Tag color="green">{overview.message_stats.total_sent}</Tag>
              </Descriptions.Item>
              <Descriptions.Item label="❌ 发送失败">
                <Tag color="red">{overview.message_stats.total_failed}</Tag>
              </Descriptions.Item>
            </Descriptions>
          </Card>
        </Col>
        <Col xs={24} lg={12}>
          <Card title="👥 在线用户分布" size="small" hoverable>
            <div style={{ marginBottom: '12px' }}>
              <Text strong>💼 C端客户 ({overview.c_users_count}):</Text>
              <div style={{ marginTop: '6px', maxHeight: '60px', overflowY: 'auto' }}>
                {overview.c_users.length > 0 ? overview.c_users.map(user => (
                  <Tag key={user} color="blue" style={{ marginBottom: '4px', fontSize: '11px' }}>
                    {user}
                  </Tag>
                )) : <Text type="secondary">暂无在线用户</Text>}
              </div>
            </div>
            <Divider style={{ margin: '8px 0' }} />
            <div>
              <Text strong>🏢 B端经理 ({overview.b_users_count}):</Text>
              <div style={{ marginTop: '6px', maxHeight: '60px', overflowY: 'auto' }}>
                {overview.b_users.length > 0 ? overview.b_users.map(user => (
                  <Tag key={user} color="purple" style={{ marginBottom: '4px', fontSize: '11px' }}>
                    {user}
                  </Tag>
                )) : <Text type="secondary">暂无在线经理</Text>}
              </div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 连接详情表格 - 核心监控区域 */}
      <Card 
        title={
          <Space>
            <WifiOutlined />
            <span>🔍 实时连接监控 ({connections.length} 个活跃连接)</span>
          </Space>
        }
        extra={
          <Space>
            <Text type="secondary">🕒 最后更新: {formatTime(timestamp)}</Text>
            {autoRefresh && <Tag color="green">🔄 自动刷新中</Tag>}
          </Space>
        }
        style={{ 
          background: '#fff',
          borderRadius: '8px',
          boxShadow: '0 4px 12px rgba(0,0,0,0.1)'
        }}
      >
        <Table
          dataSource={connections}
          columns={columns}
          rowKey={(record) => `${record.user_id}-${record.connection_uuid}`}
          pagination={{
            pageSize: 15,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `显示 ${range[0]}-${range[1]} 条，共 ${total} 个连接`,
            pageSizeOptions: ['10', '15', '25', '50'],
            size: 'small'
          }}
          size="small"
          scroll={{ 
            x: 'max-content',
            y: 'calc(100vh - 650px)'  // 动态计算表格高度
          }}
          style={{
            background: '#fff'
          }}
          rowClassName={(_record, index) => 
            index % 2 === 0 ? 'table-row-even' : 'table-row-odd'
          }
          bordered
        />
      </Card>

      {/* 全局样式优化 */}
      <style dangerouslySetInnerHTML={{
        __html: `
          /* 表格行样式优化 */
          .table-row-even {
            background-color: #fafafa !important;
          }
          .table-row-odd {
            background-color: #ffffff !important;
          }
          
          /* 表格滚动优化 */
          .ant-table-body {
            background: #fff !important;
          }
          
          /* 表格头部样式 */
          .ant-table-thead > tr > th {
            background: #f0f2f5 !important;
            font-weight: 600 !important;
            border-bottom: 2px solid #d9d9d9 !important;
          }
          
          /* 悬停效果 */
          .ant-table-tbody > tr:hover > td {
            background: #e6f7ff !important;
          }
          
          /* 卡片悬停效果 */
          .ant-card:hover {
            box-shadow: 0 6px 16px rgba(0,0,0,0.12) !important;
            transform: translateY(-1px);
            transition: all 0.3s ease;
          }
          
          /* 标签样式优化 */
          .ant-tag {
            border-radius: 4px;
            font-size: 11px;
            line-height: 18px;
          }
          
          /* 响应式优化 */
          @media (max-width: 768px) {
            .ant-table-scroll {
              overflow-x: auto !important;
            }
          }
        `
      }} />
    </div>
  );
} 